﻿using System;
using Itau.IM.Common.Interface;
using Itau.IM.Common.Logging;
using Itau.IM.Common.Utility;
using Itau.SC.Ims;

namespace Itau.IM.Common.Mainframe.Communication
{
    public class ImsTransaction
    {
        #region Atributos

        private ImsConfiguration _configuration;
        private string _routineName;

        #endregion Atributos

        #region Métodos

        /// <summary>
        /// Construtor
        /// </summary>
        public ImsTransaction(string routineName_, string transactionId_)
        {
            this._configuration = new ImsConfiguration(transactionId_);
            this._routineName = routineName_;
        }

        /// <summary>
        /// Método responsável por executar a transação IMS
        /// </summary>
        /// <param name="book_">Book de entrada</param>
        /// <returns>Book de saída</returns>
        public string Invoke(string book_)
        {
            try
            {
                //ILog log = new LogFile(this._routineName);

                //log.LogInfo("Executando transação IMS com os seguintes dados: {0}{1}",
                //    Environment.NewLine,
                //    new Serialization(typeof(ImsConfiguration)).Serialize(this._configuration));

                ScTcpIms ims = new ScTcpIms();

                int erro = ims.ComunicaIMS(this._configuration.Computer,
                    this._configuration.Port,
                    this._configuration.Ims,
                    this._configuration.Transaction.PadRight(8),
                    this._configuration.User,
                    this._configuration.Password,
                    book_);

                if (erro != 0)
                {
                    throw new Exception(String.Format("Common: Erro durante a execução da transação IMS. Reason Code: {0}, Mensagem: {1}",
                        ims.getReasonCode(),
                        ims.getMensErro()));
                }
                else
                {
                    return ims.getRecebe();
                }
            }
            catch (Exception e)
            {
                throw new Exception("Common: Erro durante a execução da transação IMS: " + e.Message, e);
            }
        }

        #endregion Métodos
    }
}